package xyz.lilei23.framework.utils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.*;

/**
 * @author lilei
 * @date 31/07/2021 16:20
 * @version 1.0
 **/
public class FileHelper {


    public  List<String> findClassByPath(String pkgName) {
        List<String> files = new ArrayList<>();
        Enumeration<URL> urls;
        try {
            String pkgPath = pkgName.replace(".", "/");
            urls = FileHelper.class.getClassLoader().getResources(pkgPath);
            while (urls.hasMoreElements()) {
                URL url = urls.nextElement();
                File file = new File(URLDecoder.decode(url.getFile(), "UTF-8"));
                getAllFilePath(pkgName, file, files);
            }
        } catch (IOException e) {
            throw new RuntimeException("路径错误:"+e.getMessage());
        }
        return files;
    }


    public void getAllFilePath(String pkgPath, File f, List<String> files) {
        Arrays.stream(Optional.ofNullable(f.listFiles(pathname -> pathname.isDirectory() || pathname.getName().endsWith("class"))).orElse(new File[0])).forEach(
                file -> {
                    String prefix = !pkgPath.equals("") ?pkgPath + ".":"";
                    if (file.isDirectory()) {
                        getAllFilePath(prefix + file.getName(), file, files);
                    } else {
                        files.add(prefix + file.getName().substring(0, file.getName().length() - 6));
                    }
                }
        );
    }
}
